package com.atguigu.guli.service.sms.controller.api;

import com.atguigu.guli.common.util.FormUtils;
import com.atguigu.guli.common.util.RandomUtils;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.sms.service.SmsService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author helen
 * @since 2020/7/4
 */
@RestController
@RequestMapping("/api/sms")
@Api(tags = "短信管理")
//@CrossOrigin //跨域
@Slf4j
public class ApiSmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("send/{mobile}")
    public R getCode(@PathVariable String mobile)  {

//        try {

            if(StringUtils.isEmpty(mobile) || !FormUtils.isMobile(mobile)){
                return R.setResult(ResultCodeEnum.LOGIN_PHONE_ERROR);
            }

            //生成验证码
            String checkCode = RandomUtils.getFourBitRandom();
            //发送验证码
//            smsService.send(mobile, checkCode);

            //将验证码存入redis
            String key = "checkCode::" + mobile;
            redisTemplate.opsForValue().set(key, checkCode, 5, TimeUnit.MINUTES);

            return R.ok().message("短信发送成功");
//        } catch (ClientException e) {
//            log.error(ExceptionUtils.getStackTrace(e));
//            throw new GuliException(ResultCodeEnum.SMS_SEND_ERROR);
//        }
    }
}
